﻿/*
 * Copyright 2011 Hanns Kucer
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;

namespace iTachToolkit
{
    internal class ClientDispatcher
    {
        private TubeDispatcher dispatcher;
        private Tube tube;
        private Recorder recorder;

		public ClientDispatcher(TubeDispatcher dispatcher, Tube tube, EndPoint endPoint, Recorder recorder)
        {
            this.dispatcher = dispatcher;
            this.tube = tube;
            this.recorder = recorder;
            ThreadPool.QueueUserWorkItem(_worker, endPoint);
        }

        void _worker(object endPoint)
        {
			Thread.CurrentThread.Name = GetType().Name;

            iTach itc = ((EndPoint)endPoint).iTachFactory();

            for (int i = 0; tube.IsConnected && itc.IsConnected; i++)
            {
                try
                {
                    // get command from client
                    string cmd = tube.Receive();

                    Transmission trx = new Transmission(cmd);

                    // trancive to acual iTach
                    string res = itc.Trancieve(cmd);

                    trx.Response = new Transmission.Command(res);

                    int m = trx.Request.Module;

                    if (recorder != null)
                        recorder.Record(trx);

                    // return respose to client
                    tube.Send(res);
                }
                catch
                {
					// for now, assume this means connection was lost, i.e.
					// the client disconnected
					break;
                }
            }

			// com here to clean up after when connection's been lost!
            itc.Close();
            dispatcher.Return(tube);
        }
    }
}
